#!/usr/bin/env python3
"""
完整测试脚本：启动ZMQ发布者、KVIndexer服务，并测试API
"""
import subprocess
import time
import signal
import os
import sys
import logging

# 获取Python解释器的完整路径
PYTHON_EXECUTABLE = sys.executable

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s [%(levelname)s] %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S'
)


def run_command_in_background(command_list, name):
    """在后台运行命令
    Args:
        command_list: 命令和参数的列表，例如 ['python3', 'script.py', '--arg1', 'value1']
        name: 进程的描述性名称
    """
    logging.info(f"启动 {name}...")
    process = subprocess.Popen(
        command_list,
        shell=False,
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        universal_newlines=True,
        preexec_fn=os.setsid  # 创建新的进程组
    )
    return process


def main():
    processes = []
    
    try:
        logging.info("=== 开始完整测试流程 ===")
        
        # 1. 启动ZMQ发布者
        zmq_process = run_command_in_background(
            [PYTHON_EXECUTABLE, "test_zmq_publisher.py"],
            "ZMQ发布者"
        )
        processes.append(("ZMQ发布者", zmq_process))
        time.sleep(2)  # 等待ZMQ发布者启动
        
        # 2. 启动KVIndexer主服务
        main_process = run_command_in_background(
            [PYTHON_EXECUTABLE, "main.py"],
            "KVIndexer主服务"
        )
        processes.append(("KVIndexer主服务", main_process))
        
        logging.info("等待服务完全启动...")
        time.sleep(8)  # 等待服务启动和ZMQ数据处理
        
        # 3. 运行API测试
        logging.info("=== 开始API测试 ===")
        api_test_process = subprocess.run(
            [PYTHON_EXECUTABLE, "test_api_client.py"],
            shell=False,
            capture_output=True,
            text=True
        )
        
        logging.info("API测试输出:")
        logging.info(api_test_process.stdout)
        if api_test_process.stderr:
            logging.error("API测试错误:")
            logging.error(api_test_process.stderr)
        
        logging.info("=== 测试完成 ===")
        logging.info("服务将继续运行，您可以:")
        logging.info("1. 查看日志输出")
        logging.info("2. 手动测试API: curl -X POST http://127.0.0.1:28080/match_sort \
            -H 'Content-Type: application/json' -d '{\"server_ip\":[\"127.0.0.1:8000\"],\"tokens\":[1,2,3]}'")
        logging.info("3. 按 Ctrl+C 停止所有服务")
        
        # 保持运行，显示日志
        logging.info("=== 实时日志输出 ===")
        while True:
            for name, process in processes:
                if process.poll() is None:  # 进程还在运行
                    try:
                        line = process.stdout.readline()
                        if line:
                            logging.info(f"[{name}] {line.strip()}")
                    except Exception as e:
                        logging.error("[%s] 读取日志错误: %s", name, e)
            time.sleep(0.1)
            
    except KeyboardInterrupt:
        logging.warning("\n收到中断信号，正在停止所有服务...")
    except Exception as e:
        logging.error(f"测试过程中出现错误: {e}")
    finally:
        # 清理所有进程
        for name, process in processes:
            if process.poll() is None:
                logging.info(f"停止 {name}...")
                try:
                    # 终止整个进程组
                    os.killpg(os.getpgid(process.pid), signal.SIGTERM)
                    process.wait(timeout=5)
                except Exception as e:
                    logging.error("[%s] 终止进程错误: %s", name, e)
                    os.killpg(os.getpgid(process.pid), signal.SIGKILL)

        logging.info("所有服务已停止")


if __name__ == "__main__":
    main()